package com.chat.datea.fragment;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chat.datea.R;
import com.chat.datea.adapter.FindFragment_ListView_Adapter;
import com.chat.datea.base.BaseFragment;
import com.chat.datea.bean.FindEntity;
import com.chat.datea.bean.SongInfos;
import com.chat.datea.utils.cache.MyConfig;
import com.chat.datea.utils.download.CommonProgressDialog;
import com.chat.datea.utils.fragment.ReplaceFragment;
import com.chat.datea.utils.volley.VolleySingleton;
import com.google.gson.Gson;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * music发现
 * Created by dllo on 15/10/20.
 */
public class FindFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private ListView find_ListView;
    private FindFragment_ListView_Adapter adapter;
    private VolleySingleton singleton;
    private ImageView search_midi;
    private CircleImageView hotList, chineseSong,
            classic, manSinger, womenSinger, combinationSinger;
    private FragmentManager manager = null;
    private AlertDialog alertDialog;
    private AlertDialog.Builder builder;
    private FindEntity entity;
    private CommonProgressDialog progressDialog;
    private ProgressDialog dialog;
    String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.learn.now&page_size=50";

    private View headView;


    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_find, null);
        headView = inflater.inflate(R.layout.headview_find, null);
        return view;
    }

    /**
     * 初始化控件
     **/
    @Override
    protected void initView() {
        find_ListView = (ListView) view.findViewById(R.id.find_ListView);
        find_ListView.addHeaderView(headView);
        hotList = (CircleImageView) headView.findViewById(R.id.hotList);
        chineseSong = (CircleImageView) headView.findViewById(R.id.chineseSong);
        classic = (CircleImageView) headView.findViewById(R.id.classic);
        manSinger = (CircleImageView) headView.findViewById(R.id.manSinger);
        womenSinger = (CircleImageView) headView.findViewById(R.id.womenSinger);
        combinationSinger = (CircleImageView) headView.findViewById(R.id.combinationSinger);
        search_midi = (ImageView) headView.findViewById(R.id.search_midi);
        search_midi.setOnClickListener(this);
        hotList.setOnClickListener(this);
        chineseSong.setOnClickListener(this);
        classic.setOnClickListener(this);
        manSinger.setOnClickListener(this);
        womenSinger.setOnClickListener(this);
        combinationSinger.setOnClickListener(this);
        find_ListView.setOnItemClickListener(this);
        //弹出对话框
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage(getActivity().getString(R.string.load_data_title));
        dialog.show();


    }

    /**
     * 初始化控件
     **/
    @Override
    protected void initData() {
        singleton = VolleySingleton.getVolleySingleton(mActivity);
        getData();

    }

    /**
     * 解析数据
     **/
    public void getData() {

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                entity = gson.fromJson(response, FindEntity.class);
                adapter = new FindFragment_ListView_Adapter(mActivity, entity);
                find_ListView.setAdapter(adapter);
                dialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        singleton.addQueue(request, "tag");

    }

    /**
     * 点击跳转对应的fragment
     **/
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hotList:
                //获得fragment管理对象
                manager = getActivity().getSupportFragmentManager();
                //new出一个对象实例
                FindJumpFragment jumpFragment = new FindJumpFragment();
                //开启一个队列
                FragmentTransaction ft = manager.beginTransaction();
                //用fragment替换占位符
                ft.replace(R.id.fl_content, jumpFragment);
                //把fragment添加到能返回的栈里
                ft.addToBackStack("");
                //提交队列
                ft.commit();
                break;
            case R.id.chineseSong:
                //获得fragment管理对象
                manager = getActivity().getSupportFragmentManager();
                //new出一个对象实例
                GoldenMelodyFragment goldenMelodyFragment = new GoldenMelodyFragment();
                //开启一个队列
                FragmentTransaction gf = manager.beginTransaction();
                //用fragment替换占位符
                gf.replace(R.id.fl_content, goldenMelodyFragment);
                //把fragment添加到能返回的栈里
                gf.addToBackStack("");
                //提交队列
                gf.commit();

                break;
            case R.id.classic:
                //获得fragment管理对象
                manager = getActivity().getSupportFragmentManager();
                //new出一个对象实例
                ClassicJumpFragment classicJumpFragment = new ClassicJumpFragment();
                //开启一个队列
                FragmentTransaction cf = manager.beginTransaction();
                //用fragment替换占位符
                cf.replace(R.id.fl_content, classicJumpFragment);
                //把fragment添加到能返回的栈里
                cf.addToBackStack("");
                //提交队列
                cf.commit();

                break;
            case R.id.manSinger:
                //获得fragment管理对象
                manager = getActivity().getSupportFragmentManager();
                //new出一个对象实例
                FragmentManSinger_jump singerJump = new FragmentManSinger_jump("0");
                //开启一个队列
                FragmentTransaction transaction = manager.beginTransaction();
                //用fragment替换占位符
                transaction.replace(R.id.fl_content, singerJump);
                //把fragment添加到能返回的栈里
                transaction.addToBackStack("");
                //提交队列
                transaction.commit();
                break;
            case R.id.womenSinger:
                FragmentManSinger_jump singer = new FragmentManSinger_jump("1");
                new ReplaceFragment(singer, getActivity().getSupportFragmentManager(), R.id.fl_content, true, null);

                break;

            case R.id.combinationSinger:

                FragmentManSinger_jump siger = new FragmentManSinger_jump("2");
                new ReplaceFragment(siger, getActivity().getSupportFragmentManager(), R.id.fl_content, true, null);

                break;
            case R.id.search_midi:
                FragmentTransaction transaction1 = getFragmentManager().beginTransaction();
                SearchFragment searchFragment = new SearchFragment();
                new ReplaceFragment(searchFragment, getActivity().getSupportFragmentManager(), R.id.fl_content, true, null);
                break;
        }
    }

    /**
     * 点击行布局进行下载
     **/
    @Override
    public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) {
        alertDialog = null;
        builder = null;
        builder = new AlertDialog.Builder(getActivity());
        if (position > 0) {
            alertDialog = builder.setTitle("系统提示是否下载")
                    .setMessage(entity.getResult().getItems().get(position - 1).getSong_title())
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(mActivity, "已取消下载", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String song_id = entity.getResult().getItems().get(position - 1).getSong_id();
                            singerLoder(song_id);
                        }
                    }).create();
            alertDialog.show();
        }
    }

    /**
     * 下载
     *
     * @param song_id
     **/
    public void singerLoder(String song_id) {

        Log.i("SONGID", "++++" + song_id);
        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json" +
                "&songid=" +
                song_id +
                "&ts=1445582673704&e=Yv077YWCp4kyKb%2FthNHwKwMq52TU6BhTuyXiIob13Do%3D&nw=2&ucf=1&res=1&l2p=0&lpb=&usup=1&lebo=0";
        //解析数据
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                SongInfos down = gson.fromJson(response, SongInfos.class);
                String show_link = down.getSongurl().getUrl().get(0).getFile_link();
                String song_title = down.getSonginfo().getTitle();
                /**弹出进度条**/
                progressDialog = new CommonProgressDialog(mActivity, handler);
                progressDialog.setMax(down.getSongurl().getUrl().get(0).getFile_size());
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();
                progressDialog.setName(song_title, down.getSonginfo().getAuthor());

                //得到的数据存入缓存
                MyConfig.putSharePre(mActivity, "link", "url", show_link);
                MyConfig.putSharePre(mActivity, "album", "title", song_title);
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Environment.getExternalStorageDirectory().getPath();
                    //获得父类里的方法
                    progressDialog.download(show_link, new File("/mnt/sdcard/Download/"));
                    Toast.makeText(mActivity, "正在下载", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        singleton.addQueue(request, "tag");

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 200) {
                progressDialog.dismiss();
                Log.i("Sysout", "handleMessage_200 ");
            }
            return false;
        }
    });
}

